﻿using System.ComponentModel.DataAnnotations;
using System.Reflection;
using System.Security.Claims;
using ApiLib.AppStart;
using ApiLib.Extras.Jwt;
using ApiLib.Helpers;
using ApiLib.Models;
using ApiLib.Utils;
using Furion;
using Furion.DataValidation;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;

namespace ApiLib.Controllers;

/// <summary>
/// 基础接口
/// </summary>
[ApiDescriptionSettings(GlobalConstants.ApiDescriptionSettings)]
public class CommonController : BaseController
{
    /// <summary>
    /// 健康检查
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet]
    public string Health()
    {
        return "ok!";
    }

    /// <summary>
    /// 获取环境
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet]
    public string Environment()
    {
        // return App.WebHostEnvironment.EnvironmentName;
        return App.HostEnvironment.EnvironmentName;
    }

    #region 基础数据

    /// <summary>
    /// 分类子项：保存子项
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public int BaseDataSave(BaseDataItem item)
    {
        if (item.Id == 0)
        {
            var info = new SysDataInfo
            {
                GroupName = item.GroupName,
                ItemName = item.ItemName,
                CreateTime = LocalTime,
                CreateUser = BaseUser?.GetSid() ?? ""
            };
            Db.Insertable(info).ExecuteReturnEntity();
            return info.Id;
        }

        var baseDataInfo = Db.Queryable<SysDataInfo>().InSingle(item.Id);
        if (baseDataInfo == null)
        {
            throw ActionException("不存在！");
        }

        baseDataInfo.GroupName = item.GroupName;
        baseDataInfo.ItemName = item.ItemName;
        baseDataInfo.UpdateTime = LocalTime;
        baseDataInfo.UpdateUser = BaseUser?.GetSid() ?? "";
        Db.Updateable(baseDataInfo).ExecuteCommand();
        return baseDataInfo.Id;
    }

    /// <summary>
    /// 分类子项：删除
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public void BaseDataDelete(int id)
    {
        var baseDataInfo = Db.Queryable<SysDataInfo>().InSingle(id);
        if (baseDataInfo == null)
        {
            // throw ActionException("不存在！");
            throw Oops.Oh("不存在！");
        }

        Db.Deleteable<SysDataInfo>().In(id).ExecuteCommand();
    }

    /// <summary>
    /// 分类子项：获取分类
    /// </summary>
    /// <returns></returns>
    public List<string> BaseDataGroups()
    {
        var groups = Db.Queryable<SysDataInfo>()
            .Distinct()
            .Select(info => info.GroupName).ToList();
        return groups;
    }

    /// <summary>
    /// 分类子项：获取列表
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public ListResponse<SysDataInfo> BaseDataItems(BaseDataItemsParam param)
    {
        var totalCount = 0;
        var infos = Db.Queryable<SysDataInfo>()
            .Where(info => info.GroupName == param.GroupName)
            .ToPageList(param.PageIndex, param.PageSize, ref totalCount);
        return new ListResponse<SysDataInfo>
        {
            List = infos,
            TotalCount = totalCount
        };
    }

    #endregion

    #region 配置项

    /// <summary>
    /// 保存配置
    /// </summary>
    /// <param name="config"></param>
    /// <returns></returns>
    public int ConfigSave(SysConfig config)
    {
        if (config.Name == "System")
        {
            throw ActionException("没有权限！");
        }

        InitAddAndUpdate(config);
        return config.Id == 0 ? Db.Insertable(config).ExecuteReturnIdentity() : Db.Updateable(config).ExecuteCommand();
    }

    /// <summary>
    /// 删除配置
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public void ConfigDel(int id)
    {
        var config = Db.Queryable<SysConfig>().InSingle(id);
        if (config == null)
        {
            throw ActionException("不存在！");
        }

        if (config.Name == "System")
        {
            throw ActionException("没有权限！");
        }

        Db.Deleteable<SysConfig>().In(id).ExecuteCommand();
    }

    /// <summary>
    /// 配置列表
    /// </summary>
    /// <returns></returns>
    public ListResponse<SysConfig> ConfigList(QueryConfigParam param)
    {
        if (param.Name == "System")
        {
            throw ActionException("没有权限！");
        }

        var configs = Db.Queryable<SysConfig>()
            .Where(config => config.Name == param.Name)
            .ToPageList(param);
        return configs;
    }

    #endregion

    #region 文件

    /// <summary>
    /// 文件上传
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [RequestFormLimits(MultipartBodyLengthLimit = int.MaxValue)]
    [RequestSizeLimit(int.MaxValue)]
    public string Upload(IFormFile file)
    {
        return SaveFile(file);
    }

    /// <summary>
    /// 附件信息
    /// </summary>
    /// <param name="id">附件ID</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public SysFileInfo FileInfo(int id)
    {
        var uploadFile = Db.Queryable<SysFileInfo>().InSingle(id);
        if (uploadFile == null)
        {
            throw ActionException("文件不存在");
        }

        return uploadFile;
    }

    /// <summary>
    /// 附件信息
    /// </summary>
    /// <param name="file">附件路径</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public SysFileInfo FileInfo([FromQuery] string file)
    {
        var uploadFile = Db.Queryable<SysFileInfo>().First(upFile => upFile.Path == file);
        if (uploadFile == null)
        {
            throw ActionException("文件不存在");
        }

        return uploadFile;
    }

    /// <summary>
    /// 附件信息
    /// </summary>
    /// <param name="files">附件路径,英文逗号分隔</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public List<SysFileInfo> FileInfos([FromQuery] string files)
    {
        var fileNames = files.Split(",");
        var uploadFiles = Db.Queryable<SysFileInfo>()
            .Where(upFile => fileNames.Contains(upFile.Path))
            .ToList();
        if (uploadFiles == null)
        {
            throw ActionException("文件不存在");
        }

        return uploadFiles;
    }


    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="id">文件ID</param>
    /// <returns></returns>
    public FileResult Download(int id)
    {
        var uploadFile = Db.Queryable<SysFileInfo>().InSingle(id);
        if (uploadFile == null)
        {
            throw ActionException("文件不存在");
        }

        var stream = GetFile(uploadFile.Path);
        return GetFileResult(stream, uploadFile.Name);
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="file">文件名</param>
    /// <returns></returns>
    public FileResult Download([FromQuery] string file)
    {
        var uploadFile = Db.Queryable<SysFileInfo>().First(upFile => upFile.Path == file);
        if (uploadFile == null)
        {
            throw ActionException("文件不存在");
        }

        var stream = GetFile(uploadFile.Path);
        return GetFileResult(stream, uploadFile.Name);
    }

    #endregion

    #region 评论

    /// <summary>
    /// 增加评论
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public int CommentAdd(SysCommentInfo info)
    {
        info.Id = 0;
        InitAddAndUpdate(info);
        var identity = Db.Insertable(info).ExecuteReturnIdentity();

        //添加提醒
        var user = GetUser(info.ReplayUser);
        if (user != null)
        {
            if (Db.Queryable<SysRemindConfig>().Any(config =>
                    config.CreateUser == user.GetSid() && config.DataType == info.DataType && config.Ignore == false))
            {
                var sysRemindInfo = new SysRemindInfo
                {
                    DataType = info.DataType,
                    DataId = identity,
                    User = user.GetSid(),
                    IsRead = false
                };
                InitAddAndUpdate(sysRemindInfo);
                Db.Insertable(sysRemindInfo).ExecuteCommand();
            }
        }

        return identity;
    }

    /// <summary>
    /// 删除评论
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public int CommentRemove(int id)
    {
        return Db.Deleteable<SysCommentInfo>()
            .Where(info => info.Id == id && info.CreateUser == CurrentUser.GetSid())
            .ExecuteCommand();
    }

    /// <summary>
    /// 评论列表
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public ListResponse<SysCommentInfo> CommentList(CommentListParam param)
    {
        var commentInfos = Db.Queryable<SysCommentInfo>()
            .Where(info => info.DataType == param.DataType && info.DataId == param.DataId)
            .OrderBy(info => info.CreateTime)
            .ToPageList(param);
        return CommentListBuild(commentInfos);
    }

    /// <summary>
    /// 评论回复列表
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public ListResponse<SysCommentInfo> CommentReplayList(CommentListDetailParam param)
    {
        var commentInfos = Db.Queryable<SysCommentInfo>()
            .Where(info => info.DataType == param.DataType && info.DataId == param.DataId)
            .Where(info => info.ReplayId == param.CommentId)
            .OrderBy(info => info.CreateTime)
            .ToPageList(param);
        return CommentListBuild(commentInfos);
    }

    /// <summary>
    /// 评论列表
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public ListResponse<SysCommentInfo> CommentMyList(PageParam param)
    {
        var sid = BaseUser?.GetSid() ?? "";
        var commentInfos = Db.Queryable<SysCommentInfo>().Where(
                info => info.CreateUser == sid)
            .OrderBy(info => info.CreateTime)
            .ToPageList(param);
        return CommentListBuild(commentInfos);
    }

    private ListResponse<SysCommentInfo> CommentListBuild(ListResponse<SysCommentInfo> res)
    {
        if (GlobalConfig.BaseAuthorization != null)
        {
            foreach (var commentInfo in res.List)
            {
                var user = GlobalConfig.BaseAuthorization.GetUser(commentInfo.ReplayUser);
                commentInfo.ReplayUserName = user?.GetName() ?? "";
                user = GlobalConfig.BaseAuthorization.GetUser(commentInfo.CreateUser);
                commentInfo.CreateUserName = user?.GetName() ?? "";
            }
        }

        return res;
    }

    #endregion

    #region 提醒

    /// <summary>
    /// 提醒配置保存
    /// </summary>
    /// <param name="config"></param>
    /// <returns></returns>
    public int RemindConfigSave(SysRemindConfig config)
    {
        InitAddAndUpdate(config);
        return Db.Insertable(config).ExecuteReturnIdentity();
    }

    /// <summary>
    /// 提醒配置删除
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public bool RemindConfigDelete(int id)
    {
        var num = Db.Deleteable<SysRemindConfig>().In(id).ExecuteCommand();
        return num > 0;
    }

    /// <summary>
    /// 提醒列表
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public ListResponse<SysRemindInfo> RemindList(PageParam param)
    {
        if (BaseUser == null)
        {
            return new ListResponse<SysRemindInfo>();
        }

        var listResponse = Db.Queryable<SysRemindInfo>().Where(info => info.User == BaseUser.GetSid())
            .OrderByDescending(info => info.CreateTime).ToPageList(param);
        foreach (var remindInfo in listResponse.List)
        {
            var baseUser = GetUser(remindInfo.CreateUser);
            remindInfo.CreateUserName = baseUser?.GetName() ?? "";
        }

        return listResponse;
    }

    /// <summary>
    /// 提醒状态改变
    /// </summary>
    /// <param name="id">提醒的ID</param>
    /// <param name="read">是否已读</param>
    /// <returns></returns>
    public bool RemindChangeRead([FromQuery] int id, [FromQuery] bool read)
    {
        var sysRemindInfo = Db.Queryable<SysRemindInfo>().InSingle(id);
        if (sysRemindInfo == null)
        {
            throw ActionException("不存在");
        }

        var sid = BaseUser?.GetSid() ?? "";
        if (sysRemindInfo.User != sid)
        {
            throw ActionException("没有权限");
        }

        sysRemindInfo.IsRead = read;
        var num = Db.Updateable(sysRemindInfo).UpdateColumns(info => new { Read = info.IsRead }).ExecuteCommand();
        return num > 0;
    }

    #endregion

    #region 收藏

    /// <summary>
    /// 收藏,{DataType,DataId}
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public bool Favor(SysFavorInfo info)
    {
        if (string.IsNullOrEmpty(info.DataType) || info.DataId == 0)
        {
            throw ActionException("数据类型或数据ID不合规");
        }

        var sid = CurrentUser.GetSid();
        var sysFavorInfo = Db.Queryable<SysFavorInfo>()
            .First(favorInfo => favorInfo.DataType == info.DataType && favorInfo.DataId == info.DataId &&
                                favorInfo.CreateUser == sid);
        if (sysFavorInfo == null)
        {
            info.Id = 0;
            info.IsDelete = false;
            info.CreateUser = sid;
            Db.Insertable(info).ExecuteCommand();
        }
        else
        {
            sysFavorInfo.UpdateUser = sid;
            sysFavorInfo.IsDelete = !sysFavorInfo.IsDelete;
            Db.Updateable(sysFavorInfo).ExecuteCommand();
        }

        return true;
    }

    /// <summary>
    /// 是否收藏,{DataType,DataId}
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public bool FavorPrimary(SysFavorInfo info)
    {
        var sid = CurrentUser.GetSid();
        var sysFavorInfo = Db.Queryable<SysFavorInfo>()
            .First(favorInfo => favorInfo.DataType == info.DataType && favorInfo.DataId == info.DataId &&
                                favorInfo.CreateUser == sid);

        return !(sysFavorInfo?.IsDelete ?? true);
    }

    /// <summary>
    /// 收藏列表
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public ListResponse<SysFavorInfo> FavorList(DataListParam param)
    {
        var sid = CurrentUser.GetSid();
        return Db.Queryable<SysFavorInfo>()
            .WhereIF(!string.IsNullOrEmpty(param.DataType), info => info.DataType == param.DataType)
            .Where(info => info.IsDelete == false && info.CreateUser == sid)
            .ToPageList(param);
    }

    #endregion

    #region 日志和时间线

    /// <summary>
    /// 增加日志
    /// </summary>
    /// <param name="log"></param>
    /// <returns></returns>
    public int LogAdd(SysLog log)
    {
        if (log.DataType == SystemKey)
        {
            throw ActionException("没有权限");
        }

        InitAddAndUpdate(log);
        return Db.Insertable(log).ExecuteReturnIdentity();
    }

    /// <summary>
    /// 日志列表
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public ListResponse<SysLog> LogList(LogListParam param)
    {
        var listResponse = Db.Queryable<SysLog>().Where(log => log.DataType == param.DataType)
            .WhereIF(param.DataId > 0, log => log.DataId == param.DataId)
            .WhereIF(!string.IsNullOrEmpty(param.Action), log => log.Action == param.Action)
            .WhereIF(!string.IsNullOrEmpty(param.CreateUser), log => log.CreateUser == param.CreateUser)
            .WhereIF(!string.IsNullOrEmpty(param.Keyword),
                log => log.Content.Contains(param.Keyword) || log.Remark.Contains(param.Keyword))
            .OrderBy(log => log.CreateTime)
            .ToPageList(param);
        foreach (var log in listResponse.List)
        {
            var user = GlobalConfig.BaseAuthorization?.GetUser(log.CreateUser);
            log.CreateUserName = user?.GetName() ?? "";
        }

        return listResponse;
    }

    /// <summary>
    /// 查询mongo日志
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public ListResponse<MongoLogInfo> LogMongoList(MongoLogParam param)
    {
        if (!MongoUtil.UseMongo)
        {
            throw ActionException("未日用mongo日志");
        }

        return MongoUtil.SearchLog(param);
    }

    #endregion

    #region 登录

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="userinfo"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    [AllowAnonymous]
    public string Login(SysUserinfo userinfo)
    {
        if (string.IsNullOrEmpty(userinfo.Username))
        {
            throw ActionException("用户名不能为空");
        }

        if (string.IsNullOrEmpty(userinfo.Password))
        {
            throw ActionException("密码不能为空");
        }

        var baseUserinfo = Db.Queryable<SysUserinfo>().First(info => info.Username == userinfo.Username);
        if (baseUserinfo == null)
        {
            throw ActionException("用户不存在");
        }

        if (!BCrypt.Net.BCrypt.Verify(userinfo.Password, baseUserinfo.Password)) throw ActionException("用户名或密码错误");
        
        var cacheKey = Guid.NewGuid().ToString("N");
        /*var user = GlobalConfig.BaseAuthorization?.GetUser(baseUserinfo.GetSid());
        if (user != null)
        {
            user.InitPermissions();
            DbHelper.SetUserCache(GlobalConstants.UserCachePrefix + cacheKey, user);
        }*/

        return JWTEncryption.Encrypt(new Dictionary<string, object>
        {
            [ClaimTypes.Sid]=baseUserinfo.Id,
            [ClaimTypes.Name]=baseUserinfo.Username,
            [ClaimTypes.Authentication]=cacheKey,
            // [ClaimTypes.UserData]=cacheKey,
        });
    }

    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="userinfo"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    [AllowAnonymous]
    public string Register(SysUserinfo userinfo)
    {
        if (string.IsNullOrEmpty(userinfo.Username))
        {
            throw ActionException("用户名不能为空");
        }

        if (string.IsNullOrEmpty(userinfo.Password))
        {
            throw ActionException("密码不能为空");
        }

        if (Db.Queryable<SysUserinfo>().Any(info => info.Username == userinfo.Username))
        {
            throw ActionException("用户已存在");
        }

        userinfo.Password = BCrypt.Net.BCrypt.HashPassword(userinfo.Password);
        Db.Insertable(userinfo).ExecuteReturnEntity();
        return "注册成功";
    }
    
    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public bool ChangePassword(ChangePasswordParam param)
    {
        if (BaseUser is not SysUserinfo user)
        {
            throw ActionException("用户未登录");
        }
        
        var userInfo=Db.Queryable<SysUserinfo>().InSingle(user.Id);
        if (userInfo==null)
        {
            throw ActionException("用户不存在");
        }

        if (!BCrypt.Net.BCrypt.Verify(userInfo.Password, param.OldPwd))
        {
            throw ActionException("密码不正确");
        }
        
        userInfo.Password = BCrypt.Net.BCrypt.HashPassword(param.NewPwd);
        Db.Updateable(userInfo).UpdateColumns(userinfo => new{userinfo.Password}).ExecuteCommand();
        return true;
    }

    #endregion

    #region 初始化

    /// <summary>
    /// 初始化数据库
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    [AllowAnonymous]
    public string InitDatabase()
    {
        if (!App.WebHostEnvironment.IsDevelopment())
        {
            return "不允许";
        }

        var projectName = Assembly.GetEntryAssembly()?.GetName().Name;
        if (!string.IsNullOrEmpty(projectName))
        {
            var ignoreColumns = GlobalConfig.IgnoreTableColumns;
            var ignoreTables = GlobalConfig.IgnoreTables;

            // var path = AppContext.BaseDirectory;
            // var lastIndexOf = path.LastIndexOf(projectName, StringComparison.Ordinal);
            // path = path[..(lastIndexOf + projectName.Length)] + "\\Modals";
            var path = Path.Combine(App.HostEnvironment.ContentRootPath, "Modals");
            var space = projectName + ".Modals";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            //默认方式
            // SqlDB.DbFirst.IsCreateAttribute().CreateClassFile(path, _namespace);
            Db.DbFirst
                //忽略
                .Where(name => !ignoreTables.Contains(name))
                //类
                // .SettingClassTemplate(old => old)
                //类构造函数
                // .SettingConstructorTemplate(old => old)
                //命名空间
                .SettingNamespaceTemplate(s => s + "\r\nusing SqlSugar;\r\nusing Npoi.Mapper.Attributes;")
                //高级自定义
                .SettingPropertyTemplate((column, temp, type) =>
                {
                    //temp中为模板，生成自定义内容后替换模板
                    //temp:{SugarColumn} public {PropertyType} {PropertyName} {get;set;}
                    //type:string
                    var columnAttribute = "\r\n           [SugarColumn({0})]";
                    var attributes = new List<string>();
                    if (column.IsPrimarykey)
                        attributes.Add("IsPrimaryKey=true");
                    if (column.IsIdentity)
                        attributes.Add("IsIdentity=true");
                    columnAttribute = attributes.Count == 0
                        ? ""
                        : string.Format(columnAttribute, string.Join(",", attributes));
                    //NPOI特性
                    var desc = column.ColumnDescription.Replace("：", ":");
                    desc = !desc.Contains(':') ? desc : desc[..desc.IndexOf(":", StringComparison.Ordinal)];
                    if (ignoreColumns.ContainsKey(column.TableName) &&
                        ignoreColumns[column.TableName].Contains(column.DbColumnName))
                    {
                        columnAttribute += "\r\n           [Ignore]";
                    }
                    else if (!string.IsNullOrEmpty(desc))
                    {
                        columnAttribute += $"\r\n           [Column(\"{desc}\")]";
                    }

                    return temp.Replace("{PropertyType}", type)
                        .Replace("{PropertyName}", column.DbColumnName)
                        .Replace("{SugarColumn}", columnAttribute);
                })
                .CreateClassFile(path, space);
            return "成功";
        }

        return "失败";
    }

    /// <summary>
    /// 初始化秘钥
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    public string InitJwtSecret(int length=64)
    {
        return EncryptUtil.GenerateRandomSecret(length);
    }

    #endregion

    #region 谷歌二次认证

    /// <summary>
    /// GoogleAuthenticator:获取手机端秘钥。已登录的移动端请求该接口获取秘钥，秘钥有效期一个小时。
    /// </summary>
    /// <returns></returns>
    public string GaMobilePhoneKey()
    {
        return GoogleAuthenticatorUtil.GetPhoneKey(BaseUser?.GetSid() ?? "");
    }

    /// <summary>
    /// GoogleAuthenticator:验证
    /// </summary>
    /// <param name="sid">用户信息</param>
    /// <param name="code">验证码</param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    [AllowAnonymous]
    public string GaLogin(string sid, string code)
    {
        if (string.IsNullOrEmpty(sid))
        {
            throw ActionException("用户名信息不全");
        }

        if (string.IsNullOrEmpty(code))
        {
            throw ActionException("验证码码不能为空");
        }

        // var baseUserinfo = Db.Queryable<SysUserinfo>().First(info => info.Username == sid);
        var baseUserinfo = GetUser(sid);
        if (baseUserinfo == null)
        {
            throw ActionException("用户不存在");
        }

        if (GoogleAuthenticatorUtil.Verify(sid, code))
        {
            return JWTEncryption.Encrypt(new Dictionary<string, object>
            {
                { ClaimTypes.Sid, baseUserinfo.GetSid() }, // 存储Id
                { ClaimTypes.Name, baseUserinfo.GetName() }, // 存储用户名
            });
        }

        throw ActionException("用户名或验证码错误");
    }

    #endregion
}

/// <summary>
/// 
/// </summary>
public class BaseDataItemsParam : PageParam
{
    /// <summary>
    /// 分组名称
    /// </summary>
    public string GroupName { get; set; } = "";
}

/// <summary>
/// 
/// </summary>
public class BaseDataItem
{
    /// <summary>
    /// ID
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// 类型名称
    /// </summary>
    public string GroupName { get; set; } = "";

    /// <summary>
    /// 子项名称
    /// </summary>
    public string ItemName { get; set; } = "";
}

/// <summary>
/// 查询配置
/// </summary>
public class QueryConfigParam : PageParam
{
    /// <summary>
    /// 配置名称
    /// </summary>
    public string Name { get; set; } = "";
}

/// <summary>
/// 查询数据类型
/// </summary>
public class DataListParam : PageParam
{
    /// <summary>
    /// 评论类型
    /// </summary>
    public string DataType { get; set; } = "";
}

/// <summary>
/// 查询评论
/// </summary>
public class CommentListParam : PageParam
{
    /// <summary>
    /// 评论类型
    /// </summary>
    [Required(ErrorMessage = "不能为空")]
    [Display(Name = "评论类型")]
    public string DataType { get; set; } = "";

    /// <summary>
    /// 评论类型ID 
    ///</summary>
    [DataValidation(ValidationTypes.PositiveNumber, ErrorMessage = "必须是正数")]
    [Display(Name = "数据ID")]
    public int DataId { get; set; }
}

/// <summary>
/// 查询评论详情
/// </summary>
public class CommentListDetailParam : CommentListParam
{
    /// <summary>
    /// 评论ID
    /// </summary>
    [DataValidation(ValidationTypes.PositiveNumber, ErrorMessage = "必须是正数")]
    [Display(Name = "评论ID")]
    public int CommentId { get; set; }
}

/// <summary>
/// 日志查询
/// </summary>
public class LogListParam : PageParam
{
    /// <summary>
    /// 评论类型
    /// </summary>
    [Required(ErrorMessage = "不能为空")]
    [Display(Name = "日志类型")]
    public string DataType { get; set; } = "";

    /// <summary>
    /// 日志类型ID 
    ///</summary>
    public int DataId { get; set; }

    /// <summary>
    /// 行为
    /// </summary>
    public string Action { get; set; } = "";

    /// <summary>
    /// 关键字：用于模糊查询
    /// </summary>
    public string Keyword { get; set; } = "";

    /// <summary>
    /// 创建人
    /// </summary>
    public string CreateUser { get; set; } = "";
}
/// <summary>
/// 修改密码的参数
/// </summary>
public class ChangePasswordParam
{
    /// <summary>
    /// 旧吗密码
    /// </summary>
    public string OldPwd { get; set; } = "";
    /// <summary>
    /// 新密码
    /// </summary>
    public string NewPwd { get; set; } = "";
}